<script setup lang="ts">
import { img2Base64 } from '@/utils/tool.ts';
import { reactive } from 'vue';

interface Emits {
  (e: 'change', value: string): void;
}

const emit = defineEmits<Emits>();

const state = reactive({
  imgUrl: ''
});

const blob2Base64 = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result); // 包含 data URL (base64)
    };
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

const changeImg = (options) => {
  if (options.fileList.length === 0) {
    return;
  }
  img2Base64(options.fileList[0].file).then(res => {
    emit('change', res);
  });
};
const clickPaste = async () => {
// 请求剪切板读取权限
  const permission = await navigator.permissions.query({ name: 'clipboard-read' });
  if (permission.state === 'granted' || permission.state === 'prompt') {
    const items = await navigator.clipboard.read();
    const imageItem = items.find(item => item.types.includes('image/png') ||
        item.types.includes('image/jpeg') ||
        item.types.includes('image/gif') ||
        item.types.includes('image/jpg') ||
        item.types.includes('image/webp'));
    if (!imageItem) {
      window.$message.error('剪切板无图片');
      return;
    }
    let blob;
    if (imageItem.types[0].startsWith('image/')) {
      blob = await imageItem.getType(imageItem.types[0]);
      state.imgUrl = URL.createObjectURL(blob);
    } else {
      throw new Error('不支持的图片类型');
    }
    blob2Base64(blob).then(result => {
      emit('change', result);
    });
  } else {
    window.$message.error('无权限读取剪切板');
  }
}
</script>

<template>
  <div>
    <n-upload
        list-type="image-card"
        :max="1"
        :default-upload="false"
        accept="image/*"
        @change="changeImg"
    />
    <n-space class="mt2">
      <n-button @click="clickPaste">粘贴图片</n-button>
      <n-image v-if="state.imgUrl" :src="state.imgUrl" width="100" height="100"></n-image>
    </n-space>
  </div>
</template>

<style scoped>

</style>
